<template>
  <div class="content">
    <el-form :inline="true" :model="formInline" class="demo-form-inline">
      <el-button type="primary" class="primaryButton" @click="addFunc()" plain>
        <i class="el-icon-plus"></i>
        添加角色
      </el-button>
      <el-form-item label="角色查询">
        <el-select v-model="formInline.roleType" placeholder="请选择角色类型">
          <el-option label="请选择角色" value=""></el-option>
          <el-option label="系统角色" value="1"></el-option>
          <el-option label="自定义角色" value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="roleListInitial">查询</el-button>
      </el-form-item>
    </el-form>
    <el-table
      :data="roleLists"
      stripe
      style="width: 100%;">
      <el-table-column
        prop="name"
        label="角色名称">
      </el-table-column>
      <el-table-column
        prop="roleType"
        label="角色类型">
        <template slot-scope="scope">
          <span v-if="scope.row.roleType == 1">系统角色</span>
          <span v-if="scope.row.roleType == 2">自定义角色</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="comment"
        label="备注">
      </el-table-column>
      <el-table-column
        prop=""
        label="操作">
        <template slot-scope="scope">
          <a class="reset" style="cursor: pointer;" @click="updateFunc(scope.$index, scope.row)">修改</a>
          <i class="line"></i>
          <a class="delete" style="cursor: pointer;" @click.stop="deleteFunc(scope.$index, scope.row)">删除</a>
        </template>
      </el-table-column>
    </el-table>
    <div class="block-page">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNo"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="pageSize"
        :pager-count="5"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <el-dialog
      title="添加角色"
      :visible.sync="centerDialogVisible"
      width="25%"
      center>
      <div class="dialogContent">
        <el-row style="width: 100%;">
          <el-col :span="24">
            <el-form :rules="rules" ref="form" :model="form" label-width="80px">
              <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name"></el-input>
              </el-form-item>
              <el-form-item label="角色类型" prop="type">
                <el-select v-model="form.type" placeholder="请选择角色类型">
                  <el-option label="请选择角色" value=""></el-option>
                  <el-option label="系统角色" :value="1"></el-option>
                  <el-option label="自定义角色" :value="2"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="备注" prop="comment">
                <el-input type="textarea" v-model="form.comment"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" v-show="addOrUpdate == 1" @click="addSave('form')">提交</el-button>
                <el-button type="primary" v-show="addOrUpdate == 2" @click="updateSave('form')">提交</el-button>
                <el-button @click="cancel('form')">关闭</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <!--<el-col :span="12">-->
            <!--<el-card :body-style="{ }" style="margin-left: 20px;">-->
              <!--<div slot="header">-->
                <!--<span>部门列表</span>-->
              <!--</div>-->
              <!--<el-tree-->
                <!--:data="departmentTreeData"-->
                <!--show-checkbox-->
                <!--node-key="id"-->
                <!--ref="departmenttree"-->
                <!--:default-expanded-keys="[]"-->
                <!--:default-checked-keys="departmentTreechecked"-->
                <!--:props="defaultProps"></el-tree>-->
            <!--</el-card>-->
          <!--</el-col>-->
        </el-row>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  // import userService from 'services/departmentService'
  export default {
    name: "role",
    data() {
      return {
        addOrUpdate:1,
        formInline: {
          roleType: '',
          code:'',
        },
        pageNo:1,
        pageSize:10,
        roleLists:[],
        roleUpdateDes:{},
        total:0,
        centerDialogVisible:false,
        form: {
          name: '',
          type: '',
          comment: ''
        },
        treeData: [],
        departmentTreeData: [],
        departmentTreechecked: [],
        defaultProps: {
          children: "children",
          label: "label"
        },
        updateDate:{},
        rules: {
          name: [
            {required: true, message: '请输入姓名', trigger: 'blur'},
            {min: 2, max: 5, message: '长度在 2 到 5 个字符', trigger: 'blur'}
          ],
          type: [
            { required: true, message: '请选择角色类型', trigger: 'change' }
          ],
          comment: [
//                      {required: true, trigger: 'blur'},
            {min: 0, max: 100, message: '长度在0 到 100 个字符', trigger: 'blur'}
          ]

        }
      }
    },
    mounted(){
      this.roleListInitial()
    },
    methods: {
      roleListInitial(){
        let roleDate = {index: this.pageNo, size: this.pageSize,roleType:this.formInline.roleType}
        userService.roleList(roleDate).then(res => {
          if (res.code == 1) {
            this.roleLists = res.list
            this.total = res.total
          }
        })
      },
      handleSizeChange(val) {
        this.pageSize = val
        this.roleListInitial()
      },
      handleCurrentChange(val) {
        this.pageNo = val
        this.roleListInitial()
      },
      addFunc(){
        this.form = {
          name: '',
          type: '',
          comment: ''
        },
          this.addOrUpdate = 1
        this.centerDialogVisible = true
        this.$nextTick(()=>{
          this.$refs.form.resetFields();
        });
        let roleAddData = {portal: 2};
        userService.roleAddTree(roleAddData).then(res => {
          if (res.code == 1) {
            let _this = this
            _this.departmentTreeData = [];
            _this.departmentTreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.departmentTreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.departmentTreeData.push(item);
            });

          }
        });
      },
      addSave(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            let params = {}
            params.name= this.form.name
            params.roleType= this.form.type
            params.comment= this.form.comment
            params.resourceCodesArray = this.$refs.departmenttree.getCheckedNodes(false,true).map(item => {return item.id})
            userService.roleAddSave(params).then(res => {
              if(res.code == 1){
                this.centerDialogVisible = false;
                this.roleListInitial()
                this.$message.success("添加角色信息成功")
              }else{
                this.$message.error("添加角色信息失败")
              }

            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      updateFunc(index,model){
        this.updateDate = model
        this.addOrUpdate = 2
        this.centerDialogVisible = true
        let roleUpdateCode = {code: model.code}
        userService.roleUpdate(roleUpdateCode).then(res => {
          if (res.code == 1) {
            this.form.name = res.model.name
            this.form.type = res.model.roleType
            this.form.comment = res.model.comment
          }
        })
        let roleUpdateType = {roleCode: model.code,type:'oem',portal:'2'}
        userService.roleUpdateTree(roleUpdateType).then(res => {

          if (res.code == 1) {
            let _this = this
            _this.departmentTreeData = [];
            _this.departmentTreechecked = [];
            function child(data) {
              if(data.state != undefined){
                _this.departmentTreechecked.push(data.id);
              }
              data.children.map(value => {
                value.label = value.text
                child(value);
              });
              data.label = data.text
            }
            res.list.map(item => {
              child(item)
              _this.departmentTreeData.push(item);
            });
          }
        });
      },
      updateSave(form){
        this.$refs[form].validate((valid) => {
          if (valid) {
            let params = {}
            params.code= this.updateDate.code
            params.name= this.form.name
            params.roleType= this.form.type
            params.comment= this.form.comment
            params.status= this.updateDate.status
            params.companyCode= this.updateDate.companyCode
            params.createTime= this.updateDate.createTime
            params.resourceCodesArray = this.$refs.departmenttree.getCheckedNodes(false,true).map(item => {return item.id})
            userService.roleUpdateSave(params).then(res => {
              if(res.code == 1){
                this.centerDialogVisible = false;
                this.roleListInitial()
                this.$message.success("修改角色信息成功，将为您刷新页面")
                setTimeout(function(){
                  window.location.reload();
                },2000)
              }else{
                this.$message.error("修改角色信息失败")
              }

            })
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      deleteFunc(index,model){
        let roleDeleteCode = {code: model.code}
        this.$confirm('此操作将删除该角色, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          userService.roleDelete(roleDeleteCode).then(res => {
            if (res.code == 1) {
              this.roleListInitial()
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });



      },
      cancel(form){
        this.$refs[form].resetFields();
        this.centerDialogVisible = false;
      },

    }
  }
</script>

<style scoped>
  .content {
    background-color: #ffffff;
    padding:10px 20px;
  }
  .primaryButton{
    margin-right: 50px;
  }
  .block-page{
    text-align: center;
  }
  .reset {
    color: #1890FF;
  }
  .delete {
    color: #F5222D;
  }
  .line {
    display: inline-block;
    width: 1px;
    background: rgba(0,0,0,0.09);
    margin: 0 11px;
    height: 14px;
  }
  .dialogContent{
    display: flex;
    flex-direction: row;
  }
</style>
